import puppeteer from 'puppeteer';
import xlsx from 'node-xlsx';
import GoLogin from '../src/gologin.js';
import readline from 'readline';
import fs from 'fs';
import request from 'request';
import { authenticator } from 'otplib';
import random from 'random-js';
import path from 'path';
import { spawn } from 'child_process';
import axios from 'axios';
import fueldo from '../my-electron-app/fueldo.js';

let isRandomMove = true;

async function exportAddresses() {
  const newPage = await gotoAddresses(await getBrowser());
  //选地址
  const addresses = await newPage.$$(
    '.fuel_Box-flex>.fuel_Box-flex>.fuel_Box-flex>.address',
  );

  for (const address of addresses) {
    const addresstext = await newPage.evaluate(address => address.textContent, address);

    if (addresstext.trim().endsWith('55b6')){
      await address.click();
    }
    console.log(addresstext);
  }
}
// promise[0].goto('h');
// const elementHandle = await page.$(
//   'input[inputmode="decimal"]',
// );
// await elementHandle.click({ clickCount: 3 })
// await elementHandle.type('0.0001',{ delay: 100 });
//
// const btn = await page.$(
//   'article+button',
// );
// await btn.click();
//
// try {
//   const div = await page.$(
//     'div[tabindex="1"]',
//   );
//   await div.click();
// } catch (e) {
//   await sleep(3000);
// }
//
// pages = await browser.pages();
// const div2 = await pages[0].$(
//   'button[type="submit"]',
// );
// await div2.click();
// await sleep(1000);
// const sum2 = await pages[0].$(
//   'button[type="submit"]',
// );
// await sum2.click();

//番茄
// await connect();
//
// await chooseWallet(browser,6);

// await refreshAccount(browser);

// pages = await browser.pages();
// const div2 = await pages[0].$(
//   'button[type="submit"]',
async function refreshAccount(browser) {
  let newPage = await browser.newPage();
  await newPage.goto('chrome-extension://dldjpboieedgcmpkchcjcbijingjcgok/popup.html#/wallet');
  try {
    const btn = await newPage.$(
      'button[intent="primary"]',
    );
    const gameName = await newPage.evaluate(btn => btn.textContent, btn);
    if (gameName.includes('Unlock')) {
      const pass = await newPage.$(
        'input[type="password"]',
      );
      await pass.click({ clickCount: 3 });
      await pass.type('!383157zhangHAO');
    }
    await btn.click();
  } catch (e) { /* empty */
  }
  await sleep(5000);

  const accs = await newPage.$(
    'button[aria-label="Accounts"]',
  );
  await accs.click();

  await sleep(1000);

  //选地址
  const head = await newPage.$$(
    '.fuel_Box-flex>.fuel_Box-flex>.fuel_Box-flex>.address',
  );
  const addresses = await newPage.$$(
    '.fuel_Box-flex>.fuel_Box-flex>.fuel_Box-flex>.address',
  );
  for (const address of addresses) {
    const addresstext = await newPage.evaluate(address => address.textContent, address);

    if (addresstext.trim().endsWith('55b6')){
      await address.click();
    }
    console.log(addresstext);
  }

  await sleep(3000);

  //领水

  // const btns = await newPage.$$(
  //   'button[intent="primary"]',
  // );
  // for (const btn of btns) {
  //   const btntext = await newPage.evaluate(btn => btn.textContent, btn);
  //
  //   if (btntext.includes('Faucet')){
  //     await btn.click();
  //   }
  // }

  //解除关联
  const button = await newPage.$(
    'button[aria-label="Menu"]',
  );
  await button.click();
  await sleep(1000);
  const Menu = await newPage.$(
    'li[data-key="connected-apps"]',
  );
  await Menu.click();
  await sleep(1000);

  const dels = await newPage.$$(
    'button[aria-label="Delete"]',
  );
  for (const item of dels) {
    await item.click();
    await sleep(1000);
    const con = await newPage.$(
      'button[aria-label="Confirm delete"]',
    );
    await con.click();
    await sleep(1000);
  }

  await newPage.close();
}

// );

async function chooseWay(page) {

}

async function connect() {
  pages = await browser.pages();
  const btnas = await pages[0].$(
    '.c-iPYhUp-ikYuPBS-css>button',
  );
  await btnas.click();
  const div = await page.$(
    'div[tabindex="1"]',
  );
  await div.click();
}

// await chooseWallet(browser);
// await move(browser);
// await chooseWallet(browser);
// await move(browser);

// clickOpt(page);
// clickApprove(browser);
// randomMove(page);

async function randomMove(page) {
  for (let i = 0; i < 1;) {
    if (isRandomMove) {
      let randomNumber = Math.floor((Math.random() * 4) + 1);
      switch (randomNumber) {
        case 1:
          await rabMove(page, 'ArrowUp');
          break;
        case 2:
          await rabMove(page, 'ArrowRight');
          break;
        case 3:
          await rabMove(page, 'ArrowDown');
          break;
        case 4:
          await rabMove(page, 'ArrowLeft');
          break;
      }
    }
    await sleep(300);
  }

}

async function moveToSell(page) {
  isRandomMove = false;
  for (let i = 0; i < 20; i++) {
    await rabMove(page, 'ArrowRight');
    await rabMove(page, 'ArrowUp');
  }
  await rabMove(page, 'ArrowLeft');

}

async function clickOpt(page) {
  for (let i = 0; i < 1;) {
    try {
      const plant = await page.$(
        '.plant-modal',
      );
      if (plant !== null) {
        const plantText = await page.evaluate(plant => plant.textContent, plant);
        if (plantText.startsWith('You don\'t')) {
          await moveToSell(page);
        }
      }

      const zz = await page.$(
        'img[src="images/tomato_seed_bag.png"]+div',
      );
      const zzs = await page.evaluate(zz => zz.textContent, zz);
      console.log(zzs);

      const cs = await page.$(
        'img[src="images/tomato.png"]+div',
      );
      const css = await page.evaluate(cs => cs.textContent, cs);
      console.log(css);

      const btn2 = await page.$$(
        'button',
      );
      let btn2Element = btn2[0];
      const btntext = await page.evaluate(btn2Element => btn2Element.textContent, btn2Element);
      if (btntext.startsWith('Buy')) {
        if (zzs < 10) {
          await btn2[0].click();
        }
        if (css > 0) {
          await btn2[1].click();
        }
        isRandomMove = true;
      } else {
        await btn2Element.click();
      }
    } catch (e) {
      // console.log(e);
    }
    await sleep(500);
  }
}

async function clickApprove(browser) {

  for (let i = 0; i < 1;) {
    try {
      pages = await browser.pages();
      let page1 = pages[pages.length - 1];
      const btn = await page1.$(
        'button[intent="primary"]',
      );
      const gameName = await page1.evaluate(btn => btn.textContent, btn);
      if (gameName.includes('Unlock')) {
        const pass = await page1.$(
          'input[type="password"]',
        );
        await pass.click({ clickCount: 3 });
        await pass.type('!383157zhangHAO');
      }

      await btn.click();

    } catch (e) { /* empty */
      // console.log(e);
    }

    await sleep(3000);
  }
}

async function move(browser) {
  const pages = await browser.pages();
  const page = pages[0];
  for (let i = 0; i < 9; i++) {
    await rabMove(page, 'ArrowDown');
  }
  await rabMove(page, 'ArrowRight');
}

async function chooseWallet(browser) {
  pages = await browser.pages();
  let page1 = pages[pages.length - 1];
  try {
    const div2 = await page1.$(
      'button[type="submit"]',
    );
    await div2.click();
  } catch (e) {
    await sleep(3000);
  }
  await sleep(10000);

  await page1.$(
    'div[aria-label="Confirm Transaction"]',
  );
  const btn = await page1.$(
    'button[intent="primary"]',
  );
  await btn.click();
}

async function rabMove(page, way) {
  await page.keyboard.down(way);
  await sleep(300);
  await page.keyboard.up(way);
}

// try {
//
// } catch (e) {
//   // await sleep(3000);
// }


async function getBrowser() {
  let wsKey = await axios.get('http://localhost:9222/json/version');
  let browser = await puppeteer.connect({
    browserWSEndpoint: wsKey.data.webSocketDebuggerUrl,
    defaultViewport: null,
  });

  return browser;
}

async function gotoAddresses(browser) {
  let newPage = await browser.newPage();
  await newPage.goto('chrome-extension://dldjpboieedgcmpkchcjcbijingjcgok/popup.html#/wallet');
  try {
    const btn = await newPage.$(
      'button[intent="primary"]',
    );
    const gameName = await newPage.evaluate(btn => btn.textContent, btn);
    if (gameName.includes('Unlock')) {
      const pass = await newPage.$(
        'input[type="password"]',
      );
      await pass.click({ clickCount: 3 });
      await pass.type('!383157zhangHAO');
    }
    await btn.click();
  } catch (e) { /* empty */
  }
  await sleep(5000);

  const accs = await newPage.$(
    'button[aria-label="Accounts"]',
  );
  await accs.click();

  await sleep(1000);

  //选地址
  const addresses = await newPage.$$(
    '.fuel_Box-flex>.fuel_Box-flex>.fuel_Box-flex>.address',
  );
  return newPage;
}

function sleep(ms) {
  return new Promise(resolve => {
    setTimeout(resolve, ms);
  });
}
